package com.xingxuecn.limit.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

/**
 * 处理返回结果的工具
 * @author Kris at 2018/9/4 11:38
 */
public class ResponseUtils {
    private static ObjectMapper om = new ObjectMapper();

    /**
     * 给请求方返回一个json。
     * @param result json的模型（一个实体对象。只要可以转为json的）
     * @param response
     */
    public static void writeJson(Object result,HttpServletResponse response){

        String json = null;
        try {
            json = om.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            json = "{code:500,msg:\"json转换错误\"}";
        }

        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(json);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.close();
        }

    }
}
